import React, { useEffect, useState, useRef } from 'react'
import axios from 'axios';
import { Button, Modal, Layout, Select, Cascader, Avatar, Badge, Space, message, Table, Input, Popconfirm } from 'antd';
import { UserAddOutlined, EditTwoTone, DeleteTwoTone, EyeTwoTone } from '@ant-design/icons';
import { Routes, Route, useNavigate, Navigate } from 'react-router-dom'
const { confirm } = Modal;
const { Search } = Input;
let fatherid = ""
export default function Index() {
    const navigate = useNavigate()
    const fatherRef = useRef(); //修改父类ref
    const newFatherRef = useRef();//新增父类 ref
    const newChildRef = useRef();//新怎子类ref
    const childRef = useRef(); //修改子类ref
    const [originData, setOriginData] = useState(0);
    const [typeList, setTypeList] = useState(); //备份
    useEffect(async () => {
        const resp = await axios.get("http://localhost:8080/qryType")
        let rs = resp.data.data.map((item, index) => {
            return (
                { id: item.fatherid, name: item.fathername, fatherid: item.fatherid }
            )
        })
        for (let i = 0; i < rs.length; i++) {
            rs[i].child = resp.data.data[i].children

        }
        console.log(rs);
        setOriginData(rs);
        setTypeList(rs)
    }, [])
    const editFather = (record) => {
        message.destroy()
        Modal.confirm({
            title: '修改类别名称',
            content: (
                <Input placeholder="输入新名称" ref={fatherRef} />
            ),
            async onOk() {
                if (fatherRef.current.state.value == undefined) {
                    message.error("请输入新名称", 1)
                    return
                }
                let params = { fatherid: record.id, newName: fatherRef.current.state.value }
                console.log(params);

                const resp = await axios.post("http://localhost:8080/editFatherTypeName", params)
                if (resp.data.state == "0") {
                    message.success(resp.data.message);
                    setTimeout(() => {
                        window.location.reload();
                    }, 500);

                } else {
                    message.error(resp.data.message);
                }


            },
        });
    }

    const addFather = () => {
        message.destroy()
        Modal.confirm({
            title: '新增类别',
            content: (
                <Input placeholder="输入类别名称" ref={newFatherRef} />
            ),
            async onOk() {
                if (newFatherRef.current.state.value == undefined) {
                    message.error("请输入名称", 1)
                    return
                }
                console.log(newFatherRef.current.state.value);
                const resp = await axios.post("http://localhost:8080/addFatherType?fatherName=" + newFatherRef.current.state.value)
                if (resp.data.state == "0") {
                    message.success(resp.data.message);
                    setTimeout(() => {
                        window.location.reload()
                    }, 500);

                } else {
                    message.error(resp.data.message);
                }
            },
        });
    }
    const delFatherType = async (record) => {
        console.log(record);
        const resp = await axios.post("http://localhost:8080/delFatherType?fatherId=" + record.id)
        if (resp.data.state == "0") {
            message.success(resp.data.message);
            setTimeout(() => {
                window.location.reload();
            }, 500);
        } else {
            message.error(resp.data.message);
        }
    }
    const editChildType = (record) => {//编辑子类名称
        Modal.confirm({
            title: '修改名称',
            content: (
                <Input placeholder="输入新名称" ref={childRef} />
            ),
            async onOk() {
                if (childRef.current.state.value == undefined) {
                    message.error("请输入名称", 1)
                    return
                }
                console.log(childRef.current.state.value);
                let params = { childid: record.childid, newChildname: childRef.current.state.value, oldChildName: record.childname }
                console.log("修改子类:", params);
                const resp = await axios.post("http://localhost:8080/editChildTypeName", params)
                if (resp.data.state == "0") {
                    message.success(resp.data.message);
                    setTimeout(() => {
                        window.location.reload()
                    }, 500);

                } else {
                    message.error(resp.data.message);
                }

            },
        });
    }
    const delChildType = async (record) => {
        console.log(record);
        const resp = await axios.post("http://localhost:8080/delChildType?childid=" + record.childid)
        if (resp.data.state == "0") {
            message.success(resp.data.message);
            setTimeout(() => {
                window.location.reload()
            }, 500);

        } else {
            message.error(resp.data.message);
        }
    }
    const addChildType = async () => {

        message.destroy()
        Modal.confirm({
            title: '新增类别',
            content: (
                <Input placeholder="输入类别名称" ref={newChildRef} />
            ),
            async onOk() {
                if (newChildRef.current.state.value == undefined) {
                    message.error("请输入名称", 1)
                    return
                }
                let params = { fatherid: fatherid, childname: newChildRef.current.state.value }
                console.log("新增子类信息:", params);
                const resp = await axios.post("http://localhost:8080/addChildTypeName", params)
                if (resp.data.state == "0") {
                    message.success(resp.data.message);
                    setTimeout(() => {
                        window.location.reload()
                    }, 500);

                } else {
                    message.error(resp.data.message);
                }
            },
        });
    }
    const childEdit = (record) => { //展开子类编辑的modal
        fatherid = record.fatherid
        Modal.info({
            title: '子类管理',
            width: '40%',
            okText: "关闭",
            content:
                <>
                    <Table
                        title={renderChildHead}
                        columns={childColumns} dataSource={record.child} bordered
                        pagination={{
                            pageSize: 4,
                        }}
                    />
                </>


        })
    }
    const columns = [
        {
            title: '分类名',
            dataIndex: 'name',
            width: '75%',

        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    <a onClick={() => { editFather(record) }}>编辑<EditTwoTone /></a>
                    <Popconfirm
                        title="删除后,该分类下的所有子类别都将删除"
                        onConfirm={() => { delFatherType(record) }}
                        okText="确定"
                        cancelText="取消"
                    >
                        <a style={{ marginLeft: 5 }}> 删除<DeleteTwoTone twoToneColor="red" /></a>
                    </Popconfirm>

                    <a onClick={() => { childEdit(record) }} style={{ marginLeft: 5 }}> 查看子类<EyeTwoTone /></a>
                </Space>
            ),
        },
    ];

    const childColumns = [
        { title: '子类别', dataIndex: 'childname', width: '50%', },
        {
            title: "操作",
            render: (text, record) => (
                <Space size="middle">
                    <a onClick={() => { editChildType(record) }}>编辑<EditTwoTone /></a>
                    <Popconfirm
                        title="删除?"
                        onConfirm={() => { delChildType(record) }}
                        okText="确定"
                        cancelText="取消"
                    >
                        <a style={{ marginLeft: 5 }}> 删除<DeleteTwoTone twoToneColor="red" /></a>
                    </Popconfirm>
                </Space>
            ),

        },


    ]


    const onSearch = (value) => {
        console.log(value);
        let rs = [];
        rs = originData.filter((item, index) => {
            console.log(item);
            return item.name.indexOf(value) != -1
        })
        console.log(rs);
        setOriginData(rs)
        if (value == null || value == "") {
            setOriginData(typeList)
        }

    }
    const renderTableHead = () => {
        return (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>分类管理</span>
                <Space>
                    <Search placeholder="搜索类别" onSearch={onSearch} allowClear style={{ width: 200 }} />
                    <Button type="primary" icon={<UserAddOutlined />} onClick={addFather}>添加分类</Button>
                </Space>
            </div>

        )
    }
    const renderChildHead = () => {
        return (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>子类管理</span>
                <Space>
                    <Button type="primary" icon={<UserAddOutlined />} onClick={addChildType}>添加子类</Button>
                </Space>
            </div>

        )
    }
    return (
        <div className="animate__animated animate__fadeIn">
            <Table columns={columns} dataSource={originData} bordered title={renderTableHead}
                pagination={{
                    pageSize: 8,
                }}
            />
        </div>
    )
}
